package flirtme.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.ans.flirtme.R;
import com.google.android.gms.internal.br;
import com.google.android.gms.internal.co;
import com.loopj.android.http.RequestParams;

import flirtme.activities.LogInActivity;
import flirtme.adapter.BroadcastMessageListAdapter;
import flirtme.adapter.ContactListAdapter;
import flirtme.constants.Constants;
import flirtme.managers.UserManager;
import flirtme.model.BroadcastContact;
import flirtme.model.BroadcastMessage;
import flirtme.model.ContactModel;
import flirtme.model.CurrentUser;
import flirtme.model.Message;
import flirtme.server.FlirtMeAsyncHttpResponseHandler;
import flirtme.server.FlirtMeRestClient;
import flirtme.widgets.NonCancellableProgressDialog;

public class BroadcastMessagesFragment extends Fragment {
	
	static List<BroadcastMessage> _messages;
	static List<BroadcastContact> _broadcastSenders;
	static ListView lv1;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
	{
		// Inflate the layout for this fragment
		View view = inflater.inflate(R.layout.activity_broadcast_messages, container, false);
		UserManager.instance().setShouldShowBroadcastMessages(false);

		if (_messages == null && _broadcastSenders ==null) {
			_messages =   new ArrayList <BroadcastMessage> ();
			_broadcastSenders = new ArrayList <BroadcastContact> ();
			getListData();
		}

		lv1 = (ListView) view.findViewById(R.id.broadcast_messages_list);
		lv1.setAdapter(new BroadcastMessageListAdapter(this.getActivity(), _messages));
		lv1.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> a, View v, int position, long id) {

				BroadcastMessage message = _messages.get(position);
				BroadcastContact contact = _broadcastSenders.get(position);

				Intent intent = new Intent(BroadcastMessagesFragment.this.getActivity(),
						flirtme.activities.BroadcastMessageActivity.class);

				intent.putExtra(Constants.MESSAGE_ID_KEY, message.getBody());
				intent.putExtra(Constants.AVATAR_URL, contact.getImageUrl());
				intent.putExtra(Constants.SENDER_ID, contact.getName());
				intent.putExtra(Constants.ADDRESS, contact.getAddress());
				startActivity(intent);
			}

		});
		return view;
	}
	

	public static void getBroadcastMessages (Context context) {
		RequestParams params = new RequestParams();
		params.put("username", UserManager.instance().getUser().getUsername());
		
		callBroadcastMessagesService(context, Constants.GET_BROADCAST_MESSAGES, params, 0, R.string.retrieve_broadcast_fail);
	}
	private void getListData() 
	{
		ArrayList<BroadcastMessage> results = new ArrayList<BroadcastMessage>();
		String hardcodedLat = "-34.6";
		String hardcodedLong = "-58.43333";
		
		getBroadcastMessages(this.getActivity());
		
		BroadcastContact sender = new BroadcastContact();
		sender.setName("Jenna J");
		sender.setImageUrl("http://sphotos-h.ak.fbcdn.net/hphotos-ak-snc7/407734_393956277340410_1881684765_n.jpg");
		sender.setLocation(hardcodedLat, hardcodedLong);
		
		ContactModel receiver = new ContactModel();
		receiver.setUsername("Francisco");
		receiver.setEmail("francisco.memoli@gmail.com");
		receiver.setDistance("10");
		receiver.setImageUrl("http://www.diariouno.com.ar/export/sites/diariouno/imagenes/2011/12/12/PRE-jelinek.jpg_2033098437.jpg");
		
		BroadcastMessage message = new BroadcastMessage( 1, "Test title", "test content", sender);
		message.setId(Long.valueOf(1));
		_messages.add(message);
		
		message = new BroadcastMessage( 2, "Test title2", "test content2", sender);
		message.setId(Long.valueOf(2));
		_messages.add(message);
		
		UserManager.instance().setBroadcastMessages(_messages);
	}
	
	
	
	public static void callBroadcastMessagesService(final Context context, final String serviceName, RequestParams params, final int successMessage, final int failMessage) 
	{

		FlirtMeRestClient.get(serviceName, params,

		new FlirtMeAsyncHttpResponseHandler(context) {
			
			NonCancellableProgressDialog dialog = new NonCancellableProgressDialog(context);
			
			
			@Override
			public void onSuccess(JSONObject response) {
				
				if (FlirtMeAsyncHttpResponseHandler.isValid(response)) 
					parseResponse (response, context);
				 else 
					Toast.makeText(context, failMessage, Toast.LENGTH_LONG).show();
				
			}
			
			@Override
			public void onFinish() {
				dialog.dismiss();
			}

			@Override
			public void onStart() {
				dialog.setMessage("Retrieving Broadcast messages...");
				dialog.show();
			}

			private void parseResponse(JSONObject response, Context context) {
				
					BroadcastMessage message;
					BroadcastContact sender;
					try {

						JSONArray payloadArray = response.getJSONArray(Constants.PAYLOAD);
						_messages.clear();
						_broadcastSenders.clear();
						for( int i = 0; i < payloadArray.length(); i++)
						{
							JSONObject broadcastData = payloadArray.getJSONObject(i);
							
							JSONObject senderData = broadcastData.getJSONObject("company");
							JSONObject profileData = senderData.getJSONObject("profile");
							String title = broadcastData.getString("title");
							String content = broadcastData.getString("text");
							String avatarUrl = senderData.getString("avatarUrl");
//							broadcastData.getString("amount");
//							broadcastData.getString("count");
							
							sender = new BroadcastContact(senderData.getString("id"), profileData.getString("name"), profileData.getString("address"), 
									profileData.getString("phone"), senderData.getString("latitud"), senderData.getString("longitud"),"");
							sender.setImageUrl(avatarUrl);
							// senderData.getString("image_url"));
							message = new BroadcastMessage( Long.parseLong(senderData.getString("id")), title, content, sender);
							_messages.add(message);
							_broadcastSenders.add(sender);
						}
						UserManager.instance().setBroadcastMessages(_messages);
						
						((Activity) context).runOnUiThread(new Runnable() {

							@Override
							public void run() {

								BroadcastMessageListAdapter _adapter = (BroadcastMessageListAdapter) lv1
										.getAdapter();
								_adapter.notifyDataSetChanged();
							}
						});

					} catch (JSONException e) {
						e.printStackTrace();
					}				
				
			}

		});
	}
	
}